<template>
	<view class="container">
		<view @click="openPopup()">
			<up-input :placeholder="placeholder" border="surround" v-model="_value"
				:customStyle="{width: '83vw',pointerEvents: 'none'}" readonly></up-input>
		</view>
		<up-datetime-picker :title="title" :show="show" v-model="dateValue" :mode="dateMode" :formatter="formatter"
			@confirm="confirm" :closeOnClickOverlay="true" @close="closePopup" @cancel="show=false" :min-date="minDate"
      :max-date="maxDate"></up-datetime-picker>
	</view>
</template>

<script>
	import {
  useUserStore
} from '@/pinia-store/user';
import {
  mapStores
} from 'pinia';

	export default {
		props: {
			value: {
				type: String,
				default: null
			},
			itemIndex: {
				type: Number,
				default: 0
			},
			placeholder: {
				type: String,
				default: '请输入内容'
			},
			format: {
				type: String,
				default: ''
			},
			title: {
				type: String,
				default: ''
			},
      ApplyDetailList: {
        type: Array,
        default: () => {
          return []
        }
      },
      itemId: {
        type: String,
        required: true
      },
      title: {
        type: String,
        default: ''
      },    
      label: {
        type: String,
        default: null
      },
      titleItems: {
        type: String,
        default: null
      },
		},
		data() {
			return {
				show: false,
				dateValue: Number(new Date()),
				dateMode: '',
				_value: '',
        minDate: null,   // ✅ 新增
        maxDate: null 
			}
		},
		watch:{
			_value: {
				handler(newValue) {
					let value = uni.getStorageSync('formData');
					var formItems = JSON.parse(value.formItems);
					formItems.forEach(item => {
						if(item.title == this.title){
							item.value = newValue;
							uni.setStorageSync(item.id, newValue);
						}
					})

				}
			}
		},
		onReady() {

		},
    created(){
      console.log('this.title',this.title);
      
    },
		computed: {
			...mapStores(useUserStore)
		},
		mounted() {
      let value = uni.getStorageSync('formData');
      let formItems = JSON.parse(value.formItems);
      formItems.forEach(item => {
        if (item.title == this.title) {
          uni.removeStorageSync(`${item.id}`);
        }
      })
      this.setechodata()
		},
		methods: {
      setechodata(){
        // 添加数据回显逻辑
        if (this.ApplyDetailList && this.ApplyDetailList.formData  && this.itemId)  {
          // 检查 formData 中是否存在当前 itemId 对应的字段 
          if (this.ApplyDetailList.formData.hasOwnProperty(this.itemId))  {
            // 获取对应的值
            const fieldValue = this.ApplyDetailList.formData[this.itemId]; 
            
            // 如果值是数组，取第一个元素（根据你的数据结构）
            if (Array.isArray(fieldValue)  && fieldValue.length  > 0) {
              this._value = fieldValue || ''
            } else {
              // 直接赋值 
              this._value = fieldValue || '';
            }
          }
        }
      },
			formatter(type, value) { //选择器格式处理
				if (this.format == 'yyyy-MM-dd') {
					this.dateMode = "date";
				} else if (this.format == 'yyyy-MM-dd HH:mm') {
					this.dateMode = "datetime";
				} else if (this.format == 'yyyy-MM') {
					this.dateMode = "year-month";
				}
				return value;
			},
			confirm(event) {
				var date = this.formatTimestampToYYMMDD(event.value);
				this._value = date;
				this.show = false;
			},
			openPopup() {
        if (this.title === '补卡时间') {
          const now = new Date();
          const currentYear = now.getFullYear();
          const currentMonth = now.getMonth(); // 0-11
          const currentDate = now.getDate();
          // 当月第一天
          const firstDayOfCurrentMonth = new Date(currentYear, currentMonth, 1);
          // 上个月第一天
          const firstDayOfLastMonth = new Date(currentYear, currentMonth - 1, 1);
          // 当月第3天
          const thirdDayOfCurrentMonth = new Date(currentYear, currentMonth, 3, 23, 59, 59);
          // 今天
          const endOfToday = new Date(currentYear, currentMonth, currentDate, 23, 59, 59);
          if (currentDate <= 3) {
            // 当月3号之前：可以选上个月1号 ~ 当月3号
            this.minDate = firstDayOfLastMonth.getTime();
            this.maxDate = thirdDayOfCurrentMonth.getTime();
          } else {
            // 当月3号之后：只能选当月1号 ~ 今天
            this.minDate = firstDayOfCurrentMonth.getTime();
            this.maxDate = endOfToday.getTime();
          }
        } else {
          // 非补卡时间，无限制
          this.minDate = new Date(2010, 0, 1).getTime();
          this.maxDate = new Date(2100, 11, 31, 23, 59, 59).getTime();
        }
				this.show = true;
			},
			closePopup() {
				this.show = false;
			},
			// 时间戳转换
			formatTimestampToYYMMDD(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear().toString();
				const month = ('0' + (date.getMonth() + 1)).slice(-2);
				const day = ('0' + date.getDate()).slice(-2);
				const hour = ('0' + date.getHours()).slice(-2);
				const minute = ('0' + date.getMinutes()).slice(-2);
				if (this.dateMode === 'date') {
					return `${year}-${month}-${day}`;
				} else if (this.dateMode === 'datetime') {
					return `${year}-${month}-${day} ${hour}:${minute}`;
				} else if (this.dateMode === 'year-month') {
					return `${year}-${month}`;
				}
				return `${year}-${month}-${day}`; // 返回 YYMMDD 格式的字符串
			}
		}
	}
</script>

<style>

</style>
